package com.kerrykidz.system.util.sync;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

/**
 * 
 * @Desc 数据同步消息类
 * @author QUINN
 * @date 2014年9月9日下午5:03:15
 */
public class DataMessage extends SyncMessage {

	public DataMessage() {
		super();
	}

	public DataMessage(SyncBean sync, String primaryValue, Map<String, Object> datas) {
		super(sync.getTableName(), sync.getPrimary(), primaryValue, datas);
	}

	public DataMessage(SyncBean sync, String primaryValue, Map<String, Object> datas, List<RelationMessage> relations) {
		super(sync.getTableName(), sync.getPrimary(), primaryValue, datas);
		super.relations = relations;
	}

	private static final long serialVersionUID = 1L;

	@Override
	public SqlAndParam getInsertSql() throws SyncDataException {
		if (StringUtils.isBlank(super.primaryKey) || StringUtils.isBlank(super.primaryValue))
			throw new SyncDataException("主键的名称和值都不允许为空");
		this.datas.remove(super.primaryKey);
		StringBuffer sql = new StringBuffer("INSERT");
		List<Object> params = new ArrayList<Object>();
		sql.append(" INTO ").append(this.tableName).append("(");
		sql.append(this.getFlds(datas.keySet())).append(")");
		if (super.isCommonTable)
			params.add(super.primaryValue);
		sql.append("VALUES(").append(this.getValues(datas.values())).append(")");
		params.addAll(datas.values());
		return new SqlAndParam(sql.toString(), params.toArray());
	}

	@Override
	public SqlAndParam getDeleteSql() throws SyncDataException {
		if (StringUtils.isBlank(super.primaryKey) || StringUtils.isBlank(super.primaryValue))
			throw new SyncDataException("主键的名称和值都不允许为空");
		StringBuffer sql = new StringBuffer("DELETE FROM ");
		sql.append(super.tableName).append(" WHERE ").append(super.primaryKey).append("=?");
		return new SqlAndParam(sql.toString(), new Object[] { super.primaryValue });
	}

	@Override
	public SqlAndParam getUpdateSql() throws SyncDataException {
		if (StringUtils.isBlank(super.primaryKey) || StringUtils.isBlank(super.primaryValue))
			throw new SyncDataException("主键的名称和值都不允许为空");
		this.datas.remove(super.primaryKey);
		StringBuffer sql = new StringBuffer("UPDATE ").append(super.tableName);
		sql.append(" SET ");
		List<Object> params = new ArrayList<Object>();
		for (String key : datas.keySet()) {
			sql.append(key).append("=?,");
			Object o = datas.get(key);
			params.add(o);
		}
		sql.delete(sql.length() - 1, sql.length());
		sql.append(" WHERE ").append(super.primaryKey).append("=?");
		params.add(super.primaryValue);
		return new SqlAndParam(sql.toString(), params.toArray());
	}
}
